package com.srwl.mytx.adapter;


import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.AdvertisementOrderDetailActivity;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.domain.AdvertisementOrder;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.service.AdvertisementOrderService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AdvertisementOrderRecordAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = "DonationRecordAdapter";
    public static final int REQUEST_CODE_SET_ADVERTISEMENT = 1000;
    public static final int REQUEST_CODE_OFFER = 2000;
    public static final int REQUEST_CODE_TO_ORDER_DETAIL = 1;
    private static final int ITEM_TYPE_NO_DATA = -1;
    private static final int ITEM_TYPE_NORMAL = 0;
    private final List<AdvertisementOrder> ordersList;
    private final Context context;


    public AdvertisementOrderRecordAdapter(Context context, List<AdvertisementOrder> ordersList) {
        this.ordersList = ordersList;
        this.context = context;

    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case ITEM_TYPE_NO_DATA:
                return new NoDataViewHolder(LayoutInflater.from(context).inflate(R.layout.no__data__layout, parent, false));
            default:
                return new OfferViewHolder(LayoutInflater.from(context).inflate(R.layout.advertisement_order_item_layout, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        if (ordersList.size() == 0) {
            return;
        }
        final AdvertisementOrder order = ordersList.get(position);
        OfferViewHolder viewHolder = (OfferViewHolder) holder;
        showAdvertisementOrder(order, viewHolder);

        viewHolder.tv_myAmount.setText(Utils.moneyFormat(order.getAmount()));
        viewHolder.itemView.setOnLongClickListener(v -> showDeleteDialog(order, position));
        viewHolder.itemView.setOnClickListener(v -> toOrderDetail(order));
    }

    private void showAdvertisementOrder(AdvertisementOrder order, OfferViewHolder viewHolder) {
//        Advertisement advertisement = order.getAdvertisement();
//        if (advertisement != null) {
//            advertisement.setoId(order.getId());//从数据库查数据的时候，没有查oId 字段，需要在这儿加上orderId,在activityResult中要使用
//            viewHolder.tv_title.setText(advertisement.getTitle());
//        }
        viewHolder.tv_orderType.setText("[广告位订单]");
        Date startTime = order.getStartDate();//订单创建时间是 广告位开始展示时间
        Date endTime = order.getEndDate();//过期时间是 广告位结束时间
        String durationTime = DateUtils.computeDurationTime( startTime,endTime);
        viewHolder.tv_duration.setText(durationTime);
        viewHolder.tv_startTime.setText(DateUtils.dateToString(startTime, DateUtils.FORMAT_TIMESTAMP));

    }

    private boolean showDeleteDialog(AdvertisementOrder order, int position) {

        ConfirmDialog dialog = new ConfirmDialog(context, "提醒", "删除订单后，该订单将不再显示", true);
        dialog.setConfirmListener(() -> deleteOrder(order, position));
        dialog.show();
        return true;
    }

    private void deleteOrder(AdvertisementOrder order, int position) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity)context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(AdvertisementOrderService.class)
                .deleteOrder(order.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        Log.d(TAG, "onResponse: 订单删除完成");
                        ordersList.remove(position);
                        notifyItemRemoved(position);
                        notifyItemRangeChanged(position, ordersList.size() - position);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });


    }

    private void toOrderDetail(AdvertisementOrder order) {
        //((Activity) context).startActivityForResult(new Intent(context, AdvertisementOrderDetailActivity.class).putExtra(Constant.EXTRA_INFO_ORDER, order), REQUEST_CODE_TO_ORDER_DETAIL);
        AdvertisementOrderDetailActivity.startActivity(context, order);
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {

        if (ordersList.size() == 0) {
            return 1;
        }
        return ordersList.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (ordersList.size() == 0) {
            return ITEM_TYPE_NO_DATA;
        }
        return ITEM_TYPE_NORMAL;
    }

    class NoDataViewHolder extends RecyclerView.ViewHolder {
        public NoDataViewHolder(View itemView) {
            super(itemView);

        }
    }


    class OfferViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_title)
        TextView tv_title;
        @BindView(R.id.tv_duration)
        TextView tv_duration;
        @BindView(R.id.tv_start_time)
        TextView tv_startTime;
        @BindView(R.id.tv_my_amount)
        TextView tv_myAmount;
        @BindView(R.id.tv_order_type)
        TextView tv_orderType;

        public OfferViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }


}